import './css/index.css';
import img1 from './img/01.jpeg';
import img2 from './img/02.jpeg';
import img3 from './img/03.jpeg';
import img4 from './img/04.jpeg';
console.log('img1', img1);
const listArr = [img1, img2, img3, img4];
function Banner($box, $Dot, $num = 4) {
  this.box = document.querySelector($box);
  this.dotBox = document.querySelector($Dot);

  // 初始值
  this.index = 1;
  this.num = $num;
  this.dotNum = 0;
  this.timer = null;
}
// 初始化图片
Banner.prototype.init = function () {
  this.box.style.backgroundImage = `url('${listArr[this.index - 1]}')`;
  next.call(this);
  prev.call(this);
  initDot.call(this);
  bindClick.call(this);
  autoPlay.call(this);
  moveFn.call(this);
};

// 初始化小圆点
function initDot() {
  for (let i = 0; i < this.num; i++) {
    let div = document.createElement('div');
    div.className = 'circle';
    this.dotBox.appendChild(div);
  }
  this.dotBox.children[this.dotNum].classList.add('active');
}

// 小圆点更新
function updateDot() {
  this.dotBox.children[this.dotNum].classList.remove('active');
  this.dotNum = this.index - 1;
  this.dotBox.children[this.dotNum].classList.add('active');
}

//小圆点点击
function bindClick() {
  let circles = this.dotBox.children;
  for (let i = 0; i < circles.length; i++) {
    circles[i].addEventListener('click', () => {
      this.index = i + 1;
      this.box.style.backgroundImage = `url('${listArr[this.index - 1]}')`;
      updateDot.call(this);
    });
  }
}

// 自动轮播
function autoPlay() {
  this.timer = setInterval(() => {
    ++this.index > 4 && (this.index = 1);
    this.box.style.backgroundImage = `url('${listArr[this.index - 1]}')`;
    updateDot.call(this);
  }, 3000);
}

// 鼠标移上定时器操控
function moveFn() {
  this.dotBox.addEventListener('mouseenter', () => {
    clearInterval(this.timer);
  });
  this.dotBox.addEventListener('mouseleave', () => {
    autoPlay.call(this);
  });
  this.box.addEventListener('mouseenter', () => {
    clearInterval(this.timer);
  });
  this.box.addEventListener('mouseleave', () => {
    autoPlay.call(this);
  });
}

// 下一张
function next() {
  let next = document.querySelector('.right');
  next.addEventListener('click', () => {
    ++this.index > 4 && (this.index = 1);
    this.box.style.backgroundImage = `url('${listArr[this.index - 1]}')`;
    updateDot.call(this);
  });
}

// 上一张
function prev() {
  let prev = document.querySelector('.left');
  prev.addEventListener('click', () => {
    --this.index < 1 && (this.index = 4);
    this.box.style.backgroundImage = `url('${listArr[this.index - 1]}')`;
    updateDot.call(this);
  });
}
let b1 = new Banner('.box', '.box-1', 4);
b1.init();
